package cc.market.controller.user;


import cc.market.constant.MessageConstant;
import cc.market.result.Result;
import cc.market.utils.AliOssUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/user/common")
@Tag(name = "文件上传接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtils aliOssUtils;

    @PostMapping("/upload")
    @Operation(summary = "上传文件接口")
    public Result<String> upload(@RequestParam Map<String, MultipartFile> files){
        List<String> arr = new ArrayList<>();
        try {
            for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
                MultipartFile file = entry.getValue(); // 获取文件对象
                if (file.isEmpty()) {
                    continue; // 如果文件为空，跳过处理
                }
                // 1. 获取文件名的后缀
                String originalFilename = file.getOriginalFilename();
                String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

                // 2. 生成 UUID
                UUID uuid = UUID.randomUUID();

                // 3. UUID 与文件名后缀拼接生成新的文件名
                String filename = uuid + substring;

                // 4. 上传到阿里云 OSS
                String filepath = aliOssUtils.upload(file.getBytes(), filename);

                // 5. 将文件的键名和上传路径保存到结果中
                arr.add(filepath);
            }
        } catch (IOException e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        String imgsURL = JSON.toJSONString(arr);
        return Result.success(MessageConstant.UPLOAD_SUCCESS,imgsURL);
    }
}
